package www.dianbaozu.com.wxapi

import androidx.hilt.lifecycle.ViewModelInject
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.flow.*
import kotlinx.coroutines.launch
import www.dianbaozu.com.R
import www.dianbaozu.com.extension.nimFlow
import www.dianbaozu.com.extension.save
import www.wen.com.common.lib.base.module.BaseViewModel
import www.wen.com.common.lib.data.entities.*
import www.wen.com.common.lib.data.repository.AppDataManager
import www.wen.com.common.lib.extension.getString
import www.wen.com.common.lib.util.SpUtil


/**
 * @author WEN
 * @Description:
 * @date 2021/9/1 10:32
 */

class WXEntryViewModel @ViewModelInject constructor(private val appDataManager: AppDataManager) :
        BaseViewModel() {

    var mLoginInfo: LoginInfo? = null


    fun wxLogin(code: String, errorAction: (LoginInfo?) -> Unit, action: (lastWxLogin: Any) -> Unit) {
        viewModelScope.launch {
            appDataManager.accessTokenFlow(code)
                    .flatMapConcat { wxResult ->
                        appDataManager.loginOrRegisterByTokenFlow(
                                "login",
                                RequestLoginOrRegisterByToken(accessToken = wxResult.data.accessToken, openId = wxResult.data.openid)
                        ) {
                            if (it.user != null) {
                                mLoginInfo = LoginInfo(it.token, it.user!!)
                                if(!it.user!!.forbidStatus){
                                    it.user!!.forbidReason
                                    SpUtil.save(it.user!!)
                                    it.token?.run { SpUtil.save(it.token!!)  }
                                    LastWxLogin(wxResult.data.openid, wxResult.data.accessToken, true, it.user!!.accId, it.user!!.accToken)
                                }else{
                                    throw Exception("账号被封禁")
                                }
                            } else {
                                LastWxLogin(wxResult.data.openid, wxResult.data.accessToken)
                            }
                        }
                    }.flatMapConcat {
                        if (it.isBind) {
                            appDataManager.nimFlow(
                                    mLoginInfo!!.user.accId,
                                    mLoginInfo!!.user.accToken
                            )
                        } else {
                            flow {
                                emit(it)
                            }
                        }
                    }
                    .onStart {
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        getString(R.string.loading_loading),
                                        LoadingDialogStateType.LOADING
                                )
                        )
                    }
                    .onCompletion { cause ->
                        if (cause == null) {
                            loading.value = UiStateCustom(
                                    stateData = LoadingDialog(
                                            tip = getString(R.string.successful_landing),
                                            loadingDialogStateType = LoadingDialogStateType.SUCCESS,
                                            isShowDialogTip = false,
                                            isShowToastTip = true
                                    )
                            )
                        }
                    }
                    .catch { cause ->
                        loading.value = UiStateCustom(
                                stateData = LoadingDialog(
                                        tip = cause.message ?: "网络异常",
                                        loadingDialogStateType = LoadingDialogStateType.ERROR,
                                        isShowDialogTip = false,
                                        isShowToastTip = (cause.message != null && cause.message != "账号被封禁")
                                )
                        )
                        mLoginInfo?.run { errorAction(this) }
                    }
                    .collect {
                        action.invoke(it!!)
                    }
        }
    }


}